package org.mobicents.servlet.sip.example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArrayList;

public class CDispatcher {
	
	private static CDispatcher instance;
	private CSender cSender;
	
	private CDispatcher()  {
		
		System.out.println("Starting Thread");
		cSender = new CSender();
		System.out.println("Creating CSender");
		Thread t = new Thread(cSender, "CSender thread 1");
		t.start();
		System.out.println("Thread started");
	}
	
	public synchronized static CDispatcher getInstance() {
	       if (instance == null) {
	               instance = new CDispatcher();
	       }
	       return instance;
	}

	/**
	*
	* @Override clone nadpisanie
	*/
	@Override
	public Object clone() throws CloneNotSupportedException {
	   throw new CloneNotSupportedException();
	}

	public synchronized void addMessageToList(CMessage cMessage) {
		System.out.println("Dodaje");
		synchronized(this){
			cSender.messageList.add(cMessage);
		}
		System.out.println("Added cMessage to LIST");
	}
	
	public synchronized CopyOnWriteArrayList<CMessage> getMessageList()
	{
		return cSender.messageList;
	}
	
	// klasa wewnetrzna implementujaca runnable do uruchamiania w watku
	private class CSender implements Runnable {

		public CopyOnWriteArrayList<CMessage> messageList = new CopyOnWriteArrayList<CMessage>();
		
		public void run() {
			
			String currDate;
			
			while(true) {
				currDate = new SimpleDateFormat("HH:mm:ss").format(new Date());			
				for (CMessage cMessage : messageList) {
					//System.out.println("Time of dispatch: " + cMessage.getTimeToDispatch());
					if(cMessage.getTimeToDispatch().equals(currDate) || cMessage.getTimeToDispatch().equals("instant")) {					
						System.out.println("CSender wysyla");
						CallBlockingSipServlet.sendMessageToGroup(cMessage.getReceivers(), cMessage.getMessage());
						
						messageList.remove(cMessage);
					}
				} 			
				
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}		
				//System.out.println("Sleeping... " + messageList.size());
			}
		}
	}
}
